package com.suneee.category.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.suneee.category.dao.CategoryDao;
import com.suneee.category.entity.Category;
import com.suneee.category.service.CategoryService;
import com.suneee.core.error.Assert;
import com.suneee.core.error.ErrorUtils;
import com.suneee.core.error.GenericException;
import com.suneee.core.util.StringUtils;
import com.suneee.resources.ProductError;

@Service("api-category")
public class CategoryServiceImpl implements CategoryService {
	@Autowired
	private CategoryDao categoryDao;

	@Override
	public void addCategory(Category category) {
		Assert.notNull(category.getName(), "分类名称");
		Assert.notNull(category.getCommisRate(), "分佣比例");

		String code = this.madeUpOfCategoryCode(category);

		String name = category.getName();
		String parentCode = StringUtils.isBlank(category.getParentCode()) ? "" : category.getParentCode().trim();
		// 判断同级目录下是子类目否重复和一级类目是否重复
		if (categoryDao.existsChildrenName(name, parentCode)) {
			throw ErrorUtils.wrap(ProductError.CHILDREN_DUPLICATE);
		}
		category.setCategoryCode(code);
		categoryDao.insert(category);
	}

	/**
	 * 生成编码
	 * 
	 * @param category
	 * @return
	 */
	private String madeUpOfCategoryCode(Category category) {
		String parentCode = category.getParentCode();
		String categoryCode = StringUtils.isBlank(parentCode) ? "" : parentCode.trim();
		if (categoryCode.length() >= 6) {
			throw ErrorUtils.wrap(ProductError.CHILDREN_ADD_DUPLICATE);
		}
		List<Map<String, Object>> list = categoryDao.getChildrenCodeListByParentCode(parentCode);

		if (list.size() >= 99) {
			throw ErrorUtils.wrap(ProductError.CHILDREN_TOO_MANY);
		} else {
			int n = 0;
			for(int i = 0;i < list.size();i++){
				String str = (String)list.get(i).get("category_code");
				str = str.substring(str.length() - 2, str.length());
				int m =	Integer.valueOf(str);
				n = n > m ? n : m;
			}
			n++;
			categoryCode = categoryCode + (n < 10 ? ("0" + n) : n);
		}
		return categoryCode;
	}

	@Override
	public void updateCategory(Category category) {
		Assert.notNull(category.getName(), "商品类目名字");
		Assert.notNull(category.getCategoryCode(), "类目编号");
		Assert.notNull(category.getCommisRate(), "分佣比例");

		String parentCode = StringUtils.isBlank(category.getParentCode()) ? "" : category.getParentCode().trim();
		String name = category.getName();
		String categoryCode = category.getCategoryCode();

		Category old = this.getCategory(categoryCode);
		if (!old.getName().equals(name) && categoryDao.existsChildrenName(name, parentCode)) {
			throw ErrorUtils.wrap(ProductError.CHILDREN_DUPLICATE);
		}
		categoryDao.update(category);
	}

	@Override
	public void deleteCategory(String... categoryCode) {
		Assert.notNull(categoryCode, "类目序号");
		try {
			List<String> idList = Arrays.asList(categoryCode);
			List<Category> list = categoryDao.select(idList);

			for (Category category : list) {
				if (category != null && categoryDao.exsitsChildNode(category.getCategoryCode())) {
					throw ErrorUtils.wrap(ProductError.CATEGORY_EXSITS_CHILD);
				}
				List<Map<String,Object>> categoryList = categoryDao.queryForList("select * from t_spec where category_code = ?", category.getCategoryCode());
				if(null != categoryList && categoryList.size() > 0)
				{
					throw ErrorUtils.wrap(ProductError.CATEGORY_CANNOT_DELETE,"规格使用了该类目，不能删除");
				}
			}
			categoryDao.delete(idList);

		} catch (GenericException e) {
			throw e;
		} catch (Exception e) {
			throw ErrorUtils.wrap(ProductError.CATEGORY_CANNOT_DELETE);
		}
	}

	/**
	 * 查询所有类目
	 */
	@Override
	public List<Category> listAll() {
		List<Category> listAll = categoryDao.listAll();

		Map<String, List<Category>> map = dvList(listAll);
		List<Category> l2 = map.get("l2");
		List<Category> l4 = map.get("l4");
		List<Category> l6 = map.get("l6");
		wrapChildren(l2, l4);
		wrapChildren(l4, l6);
		return l2;
	}

	private Map<String, List<Category>> dvList(List<Category> list) {
		List<Category> l2 = new ArrayList<>();
		List<Category> l4 = new ArrayList<>();
		List<Category> l6 = new ArrayList<>();
		for (Category cat : list) {
			int length = cat.getCategoryCode().length();
			switch (length) {
			case 2:
				cat.setLevel(1);
				l2.add(cat);
				break;
			case 4:
				cat.setLevel(2);
				l4.add(cat);
				break;
			case 6:
				cat.setLevel(3);
				l6.add(cat);
				break;
			}
		}
		Map<String, List<Category>> result = new HashMap<>();
		result.put("l2", l2);
		result.put("l4", l4);
		result.put("l6", l6);
		return result;
	}

	private void wrapChildren(List<Category> parentList, List<Category> children) {
		for (Category cat : parentList) {
			String id = cat.getCategoryCode();
			for (Category temp : children) {
				if (temp.getCategoryCode().startsWith(id)) {
					cat.getChildren().add(temp);
				}
			}
		}
	}
	

	@Override
	public List<Category> findCategory(String name) {
		if (name == null) {
			return this.listAll();
		}
		List<Category> list = categoryDao.findCategory(name);
	/*	if (list.size() != 0) {
			for (int i = 0; i < list.size(); i++) {
				Category category = list.get(i);
				String categoryCode = category.getCategoryCode();
				if (categoryCode.length() == 6) {
					category.setLevel(3);
				} else if (categoryCode.length() == 4) {
					category.setLevel(2);
				} else if (categoryCode.length() == 2) {
					category.setLevel(1);
				}
			}
		}*/
		Map<String, List<Category>> map = dvList(list);
		List<Category> l2 = map.get("l2");
		List<Category> l4 = map.get("l4");
		List<Category> l6 = map.get("l6");
		wrapChildren(l2, l4);
		wrapChildren(l4, l6);
		return l2;
	}
	

	@Override
	public Category getCategory(String categoryCode) {
		Category category = categoryDao.select(categoryCode);
		if (category.getCategoryCode().length() == 6) {
			category.setLevel(3);
		} else if (category.getCategoryCode().length() == 4) {
			category.setLevel(2);
		} else if (category.getCategoryCode().length() == 2) {
			category.setLevel(1);
		}
		return category;
	}

	/**
	 * 根据类目编码获取该类目上级名称
	 * 
	 * @param categoryCode
	 * @return
	 */
	@Override
	public String getCategoryNames(String categoryCode) {
		Category category = categoryDao.select(categoryCode);
		StringBuffer buffer = new StringBuffer();
		if (categoryCode.length() == 6) {
			String substring = categoryCode.substring(0, categoryCode.length() - 2);
			Category category1 = categoryDao.select(substring);
			String substring2 = categoryCode.substring(0, categoryCode.length() - 4);
			Category category2 = categoryDao.select(substring2);
			buffer.append(category2.getName()).append(">");
			buffer.append(category1.getName()).append(">");
			buffer.append(category.getName());
		} else if (categoryCode.length() == 4) {
			String substring = categoryCode.substring(0, categoryCode.length() - 2);
			Category category1 = categoryDao.select(substring);
			buffer.append(category1.getName()).append(">");
			buffer.append(category.getName());
		} else {
			buffer.append(category.getName());
		}
		return buffer.toString();
	}
}
